import { msgListData } from "/@/api/msg/msg";
import { store } from "/@/store";
import { ref } from "vue";
import { notification, Modal } from "ant-design-vue";
import { getToken } from "/@/utils/auth";
import router from "/@/router";
import { useUserStore } from "/@/store/modules/user";
import { useEmitter } from '/@/store/modules/user'
// import { userInfo } from "/@/types/store.d";
// src/services/websocket.js

let webSocketService = null;

export function getWebSocketService() {
  const userStore = useUserStore();
  const userCode = userStore.getUserCode;
  if (!webSocketService || userCode!== webSocketService.userCode) {
    if (webSocketService) {
      webSocketService.close();
    }
    webSocketService = new WebSocketService(userCode);
    webSocketService.connect();
    webSocketService.userCode = userCode;
  }
  return webSocketService;
}

export default class WebSocketService {
  constructor() {
    const userStore = useUserStore();
    const userCode = userStore.getUserCode;
    //console.log('userCode',userCode);
    this.url = `wss://zhxfzg.cn/wss/message-push/ws?userId=${userCode}_web`;
    this.socket = null;
    this.isConnected = false;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 1000;
    this.reconnectInterval = 2000; // 2秒重连一次
    this.params = {
      type: "heartbeat" // 可以根据服务器要求调整
    };
    console.log('WebSocketService',this.url)
  }
  connect() {
    this.socket = new WebSocket(this.url);
    //console.log(this.socket)
    //console.log(this.url)
    this.socket.onopen = () => {
      this.isConnected = true;
      this.reconnectAttempts = 0;
      //console.log('WebSocket connected');
      this.start();
    };

    this.socket.onmessage = (event) => {
      // const receiveData = JSON.stringify(event.data)
      this.handleMessage(event.data);
    };

    this.socket.onclose = () => {
      this.isConnected = false;
      console.log('WebSocket disconnected');
      this.reconnect();
      window.clearTimeout(this.heartbeatTimer)
      this.heartbeatTimer = null
    };

    this.socket.onerror = (error) => {
      // console.error('WebSocket error:', error);
      this.socket.close();
      this.reconnect();
    };
  }

handleMessage(message) {
    if ((!this.isLoginPage()) && (!message.includes('服务器收到: {"type":"heartbeat"}'))) {
        try {
            const parsedMessage = JSON.parse(message);
            let title = '消息通知';
            let description = parsedMessage.content.body;
            if (parsedMessage.content.address) {
                description = `地址${parsedMessage.content.address},${description}`;
            }
            let placement = 'bottomRight';
            let bottom = '80px';
            let top='300px'
            if (parsedMessage.type === 'fire_alarm') {
                const emitter = useEmitter();
                console.log('触发 fire-alarm-event 事件，数据为:', parsedMessage);
                emitter.emit('fire-alarm-event', parsedMessage);
            } else {
                // 添加弹窗通知
                notification.open({
                    message: title,
                    description: description, // 显示消息内容
                    placement: placement, // 弹出位置
                    bottom: bottom,
                    top: top,
                    maxCount: 10 , // 最大显示数量
                    duration: 20, // 持续时间，单位秒
                });
                // 调用语音播报功能
                const text = parsedMessage.content.body;
                //  console.log('text to speak:', text);
                this.speakMessage(text);
            }
        } catch (error) {
            // console.error('解析消息时出错:', error);
        }
    }
}
  // 语音播报功能
  speakMessage(text) {
    const msg = new SpeechSynthesisUtterance(text);

    // 设置语音属性（可选）
    msg.lang = 'zh-CN'; // 中文
    msg.voice = window.speechSynthesis.getVoices().find(voice => voice.lang === 'zh-CN' && voice.name === 'Microsoft Zhuangzi - Male');

    // 播放语音
    window.speechSynthesis.speak(msg);

    // 监听语音播放完毕事件（可选）
    msg.onend = () => {
      //console.log('语音播报完毕');
    };

    // 监听语音错误事件（可选）
    msg.onerror = (event) => {
      //console.error('语音播报出错:', event);
    };
  }
  // 判断当前页面是否为登录页
  isLoginPage() {
    const currentRoute = router.currentRoute.value;
    // 这里假设登录页的路由名称为 'login'，你需要根据实际情况修改
    return currentRoute.name === 'Login';
  }

  reconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      //console.log(`Reconnecting attempt ${this.reconnectAttempts}...`);
      setTimeout(() => this.connect(), this.reconnectInterval);
    } else {
      //console.error('Max reconnection attempts reached');
    }
  }

  send(message) {
    if (this.isConnected) {
      this.socket.send(JSON.stringify(message));
    } else {
      //console.error('WebSocket is not connected');
    }
  }

  // 发送心跳
  start() {
    this.heartbeatTimer = window.setTimeout(() => {
      if (this.socket.readyState === 1) {
        // //console.log('Sending heartbeat...'); // 添加日志输出
        this.socket.send(JSON.stringify(this.params))
        this.start()
      } else {
        this.reconnect()
      }
    }, 3000)
  }
  // 重置心跳
  reset() {
    window.clearTimeout(this.heartbeatTimer)
    this.heartbeatTimer = null
    this.start()
  }

  close() {
    this.socket.close();
  }
}    